﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Mvc;
using Free2AskModel;
using System.Web.Security;

namespace Free2AskWeb.Controllers
{
    [HandleError]
    public class VoteController : Controller
    {
        //
        // GET: /Vote/
        private Free2AskDBEntities db;
        public VoteController()
        {
            db = new Free2AskDBEntities();
        }
        public ActionResult Index()
        {
            return View();
        }

        /// <summary>
        /// 
        /// </summary>
        /// <param name="postID"></param>
        /// <param name="value">Value can only be either "+1" or "-1".</param>
        /// <returns></returns>
        public int Vote(int postID, int value)
        {
            Guid currentUserID=new Guid(Membership.GetUser().ProviderUserKey.ToString());

            var votes = from v in db.Votes
                        where v.PostID == postID && v.UserID == currentUserID
                        select v;
            if (votes.Count() == 0)
            {//The current user hasn't voted for this post. So, add a vote.

                Vote vote = new Vote();
                vote.PostID = postID;
                vote.UserID = currentUserID;
                vote.Value = value;

                db.Votes.AddObject(vote);
                db.SaveChanges();
            }
            else
            {//Already voted.
                var vote=votes.Single();
                if (value != vote.Value)
                {//The current value negates the vote. Remove the vote.
                    db.Votes.DeleteObject(vote);
                    db.SaveChanges();
                }
                else
                {
                    throw new Exception("Already voted.");
                }
            }    

            Post post=db.Posts.Single(p => p.ID == postID);
            int? sum= post.Votes.Sum(v => v.Value);
            if (sum != null)
            {
                return (int)sum;
            }
            else
            {
                return 0;
            }
        }

    }
}
